package com.example.redis.spring.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

//TODO 企业中可以直接使用
@Configuration
public class RedisConfig {

	//编写我们自己的redisTemplate
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

		//JSON 序列化
		Jackson2JsonRedisSerializer jsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);

		ObjectMapper om=new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jsonRedisSerializer.setObjectMapper(om);

		StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();

		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		//hashkey 采用String的序列化方式
		template.setHashKeySerializer(stringRedisSerializer);
		//Value 序列化采用JackJson
		template.setValueSerializer(jsonRedisSerializer);
		//key采用String的序列化方式
		template.setKeySerializer(stringRedisSerializer);


		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

}
